/**
 *    https://gitee.com/gitsc/pro-cloud/
 *     @Author Aijm 2929793435@qq.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.cloud.auth.handler;

import com.cloud.auth.entity.SysTenant;
import com.cloud.auth.service.SysTenantService;
import com.cloud.common.data.util.ServletUtil;
import com.cloud.common.oauth.exception.TentantException;
import com.cloud.common.oauth.properties.SecurityProps;
import com.cloud.common.util.var.StatusVar;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 处理租户是否停用
 * @author Aijm
 * @since 2020/5/24
 */
@Slf4j
@Component
@AllArgsConstructor
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantSatausFilter extends OncePerRequestFilter {

    private final SysTenantService sysTenantService;

    private final SecurityProps securityProps;


    /**
     * 失败处理器
     */
    private final AuthenticationFailureHandler authenticationFailureHandler;


    /**
     * 判断租户是否停用或者错误的租户id
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        //  获取到租户详细信息
        String clientId = ServletUtil.getClientId(securityProps.getClient().getClientId());
        // 获取到 对应的 租户信息
        SysTenant sysTenant = sysTenantService.getSysTenant(clientId);
        if (sysTenant == null || sysTenant.getStatus().intValue() == StatusVar.STATUS_DOWN.intValue()) {
            authenticationFailureHandler.onAuthenticationFailure(request, response, new TentantException("租户停用中!"));
            return;
        }
        chain.doFilter(request, response);
    }



}